/*
 *
 *  * Copyright (C) 2014 Antonio Leiva Gordillo.
 *  *
 *  * Licensed under the Apache License, Version 2.0 (the "License");
 *  * you may not use this file except in compliance with the License.
 *  * You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an "AS IS" BASIS,
 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  * See the License for the specific language governing permissions and
 *  * limitations under the License.
 *
 */

package tw.asap.plus.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.igexin.sdk.PushManager;

import tw.asap.plus.R;
import tw.asap.plus.common.ConstValue;
import tw.asap.plus.presenter.LoginPresenter;
import tw.asap.plus.presenter.LoginPresenterImpl;
import tw.asap.plus.presenter.LoginView;
import tw.asap.plus.ui.BaseActivity;
import tw.asap.plus.utils.AppManager;
import tw.asap.plus.utils.SPUtil;
import tw.asap.plus.utils.SecurityUtil;
import tw.asap.plus.utils.Toaster;


public class LoginActivity extends BaseActivity implements LoginView, View.OnClickListener {


    private static final String TAG = "LoginActivity";
    private CheckBox cbRemenberPasswd;
    private ProgressBar progressBar;
    private EditText mUsername;
    private EditText mPassword;
    private LoginPresenter presenter;
    private TextView button;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setHasAppBar(false);
        // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
        PushManager.getInstance().initialize(this.getApplicationContext());
//        UmengUpdateAgent.silentUpdate(this);

        if (hasLoginForm()) {
            startWebActivity();
        }

        progressBar = (ProgressBar) findViewById(R.id.progress);
        mUsername = (EditText) findViewById(R.id.username);
        mPassword = (EditText) findViewById(R.id.password);
        button = (TextView) findViewById(R.id.button);
        cbRemenberPasswd = (CheckBox) findViewById(R.id.cb_remenber_passwd);

        mUsername.setText(username);
        mPassword.setText(password);
        cbRemenberPasswd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                spUtil.save(ConstValue.Sp.REMENBER_PASS_CHECKED, isChecked);
            }
        });

        button.setOnClickListener(this);

        presenter = new LoginPresenterImpl(this);

        spUtil = SPUtil.getInstance(LoginActivity.this.getApplicationContext());

        if (spUtil.getBoolean(ConstValue.Sp.REMENBER_PASS_CHECKED, true) == true) {
            cbRemenberPasswd.setChecked(true);
            String encodepasswd = spUtil.getString(ConstValue.Sp.ENCRPT, "");
            String decodePass = SecurityUtil.decodeBase64(encodepasswd);
            mPassword.setText(decodePass);
        } else {
            cbRemenberPasswd.setChecked(false);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void showProgress() {
        progressBar.setVisibility(View.VISIBLE);
        button.setEnabled(false);
    }

    @Override
    public void setUsernameError() {
        progressBar.setVisibility(View.GONE);
        mUsername.requestFocus();
        mUsername.setError(getString(R.string.username_error));
        mPassword.setError(null);
        button.setEnabled(true);
    }

    @Override
    public void setPasswordError() {
        progressBar.setVisibility(View.GONE);
        mPassword.requestFocus();
        mPassword.setError(getString(R.string.password_error));
        mUsername.setError(null);
        button.setEnabled(true);
    }

    @Override
    public void onSuccess() {
        progressBar.setVisibility(View.GONE);
        // 登录成功
        button.setEnabled(true);
        spUtil.save(ConstValue.Sp.USERNAME, username);
        spUtil.save(ConstValue.Sp.SESSIONID, username);
//        spUtil.save(ConstValue.Sp.SESSIONID, UserInfo.getInstance().getSessionid());
//        User.cacheSessionID(UserInfo.getInstance().getSessionid());
        if (cbRemenberPasswd != null && cbRemenberPasswd.isChecked()) {
            String encodePasswd = SecurityUtil.encodeBase64(mPassword.getText().toString());
            spUtil.save(ConstValue.Sp.ENCRPT, encodePasswd);
        }
//        spUtil.save(ConstValue.Sp.PASSWORD, password);
        startWebActivity();
    }


    @Override
    public Context getContext() {
        return LoginActivity.this;
    }

    @Override
    public void onFailed(String resperr) {
        // 登录失败
        button.setEnabled(true);
        progressBar.setVisibility(View.GONE);
        if (TextUtils.isEmpty(resperr)) {
            resperr = getString(R.string.text_login_fail);
        }
        Toaster.s(LoginActivity.this, resperr);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                username = mUsername.getText().toString();
                password = mPassword.getText().toString();
                presenter.login(username, password);
                break;
        }
    }


    private void startWebActivity() {
        Intent intent = new Intent(LoginActivity.this, WebActivity.class);
//        intent.putExtra("webURL", ConstValue.H5_MAIN_WEBURL);
        startActivity(intent);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AppManager.finishAllActivity();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
}
